package com.book.system.dao;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class BaseDao {

    /**
     * 数据源对象
     */
    private static DataSource dataSource = null;

    /**
     * 数据源初始化
     */
    static {
        try {
            //创建资源对象
            Properties properties = new Properties();
            //读取配置文件 通过类加载
            properties.load(BaseDao.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     *
     * @return
     * @throws SQLException
     */
    private static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
//        Connection connection = dataSource.getConnection();
//        return connection;
    }

    /**
     * 对数据库的修改操作  返回影响的数据条数
     *
     * @param sql  SQL语句
     * @param data 参数列表
     * @return int
     */
    public static int executeUpdate(String sql, Object... data) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            //对预编译sql进行赋值   预编译下表从1开始 所以 i+1
            for (int i = 0; i < data.length; i++) {
                ps.setObject(i + 1, data[i]);
            }
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            close(conn, ps, null);
        }
        return 0;
    }

    /**
     * 数据库的查询操作  返回查询结果
     *
     * @param sql
     * @param data
     * @return list
     */
    public static List<Map<String, Object>> executeQuery(String sql, Object... data) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < data.length; i++) {
                ps.setObject(i + 1, data[i]);
            }
            rs = ps.executeQuery();
            int count = rs.getMetaData().getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= count; i++) {
                    String name = rs.getMetaData().getColumnLabel(i);
                    Object values = rs.getObject(i);
                    map.put(name, values);
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, ps, rs);
        }
        return list;
    }


    /**
     * 释放资源
     *
     * @param conn
     * @param ps
     * @param rs
     */
    private static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public static <T> T convert(Map<String, Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        T entity = clazz.newInstance();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            try {
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method setter = clazz.getMethod(setterName, fieldValue.getClass());
                setter.invoke(entity, fieldValue);
            } catch (Exception e) {
                // 异常处理，例如记录日志或忽略某些属性
            }
        }
        return entity;
    }

}
